package pojo;

import io.jsonwebtoken.*;

import java.util.ArrayList;
import java.util.Date;

public class TokenUtils {
    public static Integer SUCCESS = 0;
    public static Integer ERROR_SIGN = 1;
    public static Integer ERROR_EXPIRE = 2;
    public static Integer ERROR = 3;

    private String key = "123456";
    private Integer expireTime = 60;
    private Claims claims = null;

    public static TokenUtils token() {
        return new TokenUtils();
    }

    public TokenUtils setKey(String key) {
        this.key = key;
        return this;
    }

    public TokenUtils setExpire(Integer seconds) {
        this.expireTime = seconds;
        return this;
    }

    public String createToken(String... keyValues) {
        JwtBuilder builder = Jwts.builder();
        // 设置签发日期
        builder.setIssuedAt(new Date());
        // 设置过期时间
        long now = System.currentTimeMillis();
        long exp = now+1000*expireTime;
        builder.setExpiration( new Date( exp ) );

        // 添加数据
        ArrayList<String> stringPair = new ArrayList<>();
        for(String kv:keyValues) {
            // 添加键值对
            stringPair.add(kv);
            //
            if(stringPair.size()>=2) {
                builder.claim( stringPair.get(0),stringPair.get(1) );
                stringPair.clear();
                continue;
            }

        }

        //
        // 设置签名 使用HS256算法，并设置SecretKey(字符串)
        builder.signWith(SignatureAlgorithm.HS256,key);

        // 生成token
        String token = builder.compact();

        return token;
    }

    public Integer parseToken(String token) {
        try {
            claims = Jwts.parser()
                    .setSigningKey(key)
                    .parseClaimsJws(token)
                    .getBody();
            return TokenUtils.SUCCESS;
        }
        catch (ExpiredJwtException e) {
            System.out.println("token expired");
            return TokenUtils.ERROR_EXPIRE;
        } catch (SignatureException e) {
            System.out.println("token signature error");
            return TokenUtils.ERROR_SIGN;
        } catch (Exception e) {
            System.out.println("token error");
            return TokenUtils.ERROR;
        }
    }

    public String getClaim(String key) {
        if(claims == null) {
            return null;
        }

        Object o = claims.get(key);

        return claims.get(key).toString();
    }
}
